<?php

namespace app\service;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

class HomeService
{
    public static ?HomeService $_instance = null;

    /**
     * @return HomeService|null
     */
    public static function instance(): ?HomeService
    {
        if (!static::$_instance) static::$_instance = new self();
        return static::$_instance;
    }

    /**
     * @param int $max_length
     * @return bool|string
     */
    public function setCaptcha(int $max_length = 4): bool|string
    {
        $phrase = new PhraseBuilder($max_length, '0123456789');
        // 初始化验证码类
        $builder = new CaptchaBuilder($phrase->build($max_length), $phrase);
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        request()->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        return $builder->get();
    }

    /**
     * 获取二级域名前缀
     *
     * @return string
     */
    public function get_second_host(): string
    {
        $host       = request()->host();
        $host_array = explode('.', $host);
        return count($host_array) >= 3 ? $host_array[0] : WEB_WWW;
    }
}